package com.leonwoodstudio.endorsementclient;

import android.os.Handler;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * Created by win7 on 2017/3/17.
 */
public class ReceiveFileThread extends Thread {
    Socket client;
    Handler handler;
    public ReceiveFileThread(Socket client, Handler handler) {
        this.client = client;
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();
        BufferedInputStream bis = null;
        try {
            InputStream is = client.getInputStream();
            bis = new BufferedInputStream(is);
            // read command type, 0 - xml, 1 - pic, 2 - fail
            byte[] command = new byte[4];
            bis.read(command, 0, 4);
            int command_type = Util.byteArray2Int(command);
            System.out.println(command_type);

            // read file name length
            byte[] len = new byte[4];
            bis.read(len, 0, 4);
            int name_len = Util.byteArray2Int(len);
            System.out.println(name_len);
            if (name_len <= 0 || name_len > 40) {
                handler.obtainMessage(MainService.MSG_RECV_FAIL, null).sendToTarget();
                return;
            }
            // read file name string
            byte[] name = new byte[name_len];
            bis.read(name, 0, name_len);
            String name_str = new String(name, "GBK");
            System.out.println(name_str);

            // read file length
            bis.read(len, 0, 4);
            int content_len = Util.byteArray2Int(len);
            if (name_len <= 0) {
                handler.obtainMessage(MainService.MSG_RECV_FAIL, null).sendToTarget();
                return;
            }
            // read file content
            byte[] content = new byte[content_len];
            int received;
            int cur = 0;
            int left = content_len;
            while ((received = bis.read(content, cur, left)) != -1) {
                cur += received;
                left -= received;
                if (left == 0) {
                    break;
                }
            }
            if (left == 0) {
                FileAccessor.getInstance(null).writeSdFile(FileAccessor.getInstance(null).getFilesDir() + name_str, content);
                handler.obtainMessage(command_type, name_str).sendToTarget();
            } else {
                handler.obtainMessage(MainService.MSG_RECV_FAIL, null).sendToTarget();
            }
        } catch (IOException e) {
            handler.obtainMessage(MainService.MSG_RECV_FAIL, null).sendToTarget();
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
